package lc.com.lcpicturebackend.api.aliyun.model;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import lc.com.lcpicturebackend.exception.BusinessException;
import lc.com.lcpicturebackend.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 功能：
 * 作者：lc
 * 日期：2025/3/3 19:52
 */
@Slf4j
@Component
public class AliYunApi {
    @Value("${aliYunAi.apiKey}")
    private String apiKey;

    // 创建任务地址
    private static final String CREATE_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/out-painting";
    // 查询任务状态
    private static final String QUERY_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/tasks/%s";

    // 创建任务
    public CreateOutPaintingTaskResponse createTask(CreateOutPaintingTaskRequest createOutPaintingTaskRequest) {
        if (ObjectUtil.isEmpty(createOutPaintingTaskRequest)) {
            throw new RuntimeException("请求参数不能为空");
        }
        HttpRequest request = HttpRequest.post(CREATE_TASK_URL)
                .header("Authorization", "Bearer " + apiKey)
                .header("X-DashScope-Async", "enable")
                .header("Content-Type", "application/json")
                .body(JSONUtil.toJsonStr(createOutPaintingTaskRequest));
        try (HttpResponse httpResponse = request.execute()) {
            if (!httpResponse.isOk()) {
                log.error("接口调用失败, 响应信息: {}", httpResponse.body());
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "接口调用失败");
            }
            CreateOutPaintingTaskResponse response = JSONUtil.toBean(httpResponse.body(), CreateOutPaintingTaskResponse.class);
            String errorCode = response.getCode();
            if (!StrUtil.isBlank(errorCode)) {
                String errorMessage = response.getMessage();
                log.error("AI 扩图失败，errorCode:{}, errorMessage:{}", errorCode, errorMessage);
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "AI 扩图接口响应异常");
            }
            return response;
        }
    }

    // 查询创建的任务
    public GetOutPaintingTaskResponse getOutPaintingTask(String taskId) {
        if (StrUtil.isEmpty(taskId)) {
            throw new RuntimeException("请求参数不能为空");
        }

        try (HttpResponse response = HttpRequest.get(String.format(QUERY_TASK_URL, taskId))
                .header("Authorization", "Bearer " + apiKey)
                .execute()) {
            if (!response.isOk()){
                log.error("查询任务失败:{}", response.body());
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询任务失败");
            }
            return  JSONUtil.toBean(response.body(), GetOutPaintingTaskResponse.class);
        }
    }
}
